package com.liuqi.knet.util;

import java.io.ByteArrayOutputStream;
import java.io.PrintWriter;

/**
 * @author liuqi
 * @date 2024/12/13 14:38
 **/
public final class CommonUtil {

    private static final char[] randomChar = new char[] {
            'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
            'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'
    };

    /**
     * @param length
     * @return  生成<code>length</code>位随机数
     */
    public static String random(int length) {
        int size = randomChar.length;
        StringBuilder buf = new StringBuilder(length);
        for (int i = 0; i < length; i++) {
            int index = (int) (Math.random() * size);
            buf.append(randomChar[index]);
        }
        return buf.toString();
    }

    /**
     * @param e
     * @return  异常消息转换为String
     */
    public static String toString(Throwable e) {
        ByteArrayOutputStream buf = new ByteArrayOutputStream();
        PrintWriter writer = new PrintWriter(buf);
        try {
            e.printStackTrace(writer);
        } finally {
            writer.close();
        }
        return buf.toString();
    }

    public static String toString(Object[] objects) {
        if (objects == null) {
            return null;
        }
        StringBuilder buf = new StringBuilder("[");
        for (Object obj : objects) {
            buf.append(obj).append(", ");
        }
        buf.append("]");

        return buf.toString();
    }

    public static <T> T checkNotNull(T arg, String text) {
        if (arg == null) {
            throw new NullPointerException(text);
        }
        return arg;
    }

}
